<?php
/**
 * Created by IntelliJ IDEA.
 * User: kaireewu
 * Date: 11-9-29
 * Time: 下午3:04
 * To change this template use File | Settings | File Templates.
 */
 if(!defined('IN_SYS')){
     exit('Access Denied');
 }
define('CORE_FUNCTION', true);

function getgpc($k, $type='PG') {
    $type = strtoupper($type);
    switch($type) {
        case 'G': $var = &$_GET;
            break;
        case 'P': $var = &$_POST;
            break;
        case 'C': $var = &$_COOKIE;
            break;
        default:
            if(isset($_POST[$k])) {
                $var = &$_POST;
            } else {
                $var = &$_GET;
            }
            break;
    }
    return isset($var[$k]) ? $var[$k] : NULL;
}

function daddslashes($string, $force = 1) {
    if(is_array($string)) {
        $keys = array_keys($string);
        foreach($keys as $key) {
            $val = $string[$key];
            unset($string[$key]);
            $string[addslashes($key)] = daddslashes($val, $force);
        }
    } else {
        $string = addslashes($string);
    }
    return $string;
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    $ckey_length = 4;
    $key = md5($key != '' ? $key : getglobal('authkey'));
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key,16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb),0, 16).$string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

function dhtmlspecialchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dhtmlspecialchars($val);
		}
	} else {
		$string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
		if(strpos($string, '&amp;#') !== false) {
			$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
		}
	}
	return $string;
}

function getglobal($key, $group = null) {
    global $_G;
    $k = explode('/', $group == null ? $key : $group.'/'.$key);
    switch (count($k)) {
        case 1: return isset($_G[$k[0]]) ? $_G[$k[0]] : null; break;
		case 2: return isset($_G[$k[0]][$k[1]]) ? $_G[$k[0]][$k[1]] : null; break;
		case 3: return isset($_G[$k[0]][$k[1]][$k[2]]) ? $_G[$k[0]][$k[1]][$k[2]] : null; break;
		case 4: return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]] : null; break;
		case 5: return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] : null; break;
    }
    return null;
}

function random($length, $numeric = 0) {
	$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed{mt_rand(0, $max)};
	}
	return $hash;
}

function get_script_url() {
    $php_self = '';
    if($_SERVER['PHP_SELF'] === null){
        $scriptName = basename($_SERVER['SCRIPT_FILENAME']);
        if(basename($_SERVER['SCRIPT_NAME']) === $scriptName) {
            $php_self = $_SERVER['SCRIPT_NAME'];
        } else if(basename($_SERVER['PHP_SELF']) === $scriptName) {
            $php_self = $_SERVER['PHP_SELF'];
        } else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) {
            $php_self = $_SERVER['ORIG_SCRIPT_NAME'];
        } else if(($pos = strpos($_SERVER['PHP_SELF'],'/'.$scriptName)) !== false) {
            $php_self = substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
        } else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT']) === 0) {
            $php_self = str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
        } else {
            die('request_tainting');
        }
    }
    return $php_self;
}

function get_site_url() {
    $url = substr(get_script_url(), 0, strrpos(get_script_url(), '/'));
    $site_root = htmlspecialchars('http://'.$_SERVER['HTTP_HOST']);
    $site_port = empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' ? '' : ':'.$_SERVER['SERVER_PORT'];
    $site_url = $site_root . $site_port . $url;
}
function checkLogin($cookiePre = 'isux') {
    $sessionKey = $cookiePre . '_user';
    global $user;
    if(isset($_SESSION[$sessionKey]) && is_array($_SESSION[$sessionKey])) {
        $user = $m_user = $_SESSION[$sessionKey];
        return true;
    }
    return false;
}

function doLogin($uname, $upass, $cookiePre='isux') {
    global $db;
    if($db){
        $result = $db->prepare("SELECT uid, uname, upass, email, nickname, url FROM members WHERE uname = :uname");
        $result->bindParam(':uname', $uname, PDO::PARAM_STR);
        $result->execute();
        $member = $result->fetch(PDO::FETCH_ASSOC);
        if($member) {
            $upass = md5($upass);
            if($uname == $member['uname'] && $upass == $member['upass']) {
                $sessionKey = $cookiePre . '_user';
                global $logined, $user;
                $_SESSION[$sessionKey] = $user = $member;
                $logined = true;
                return true;
            }
        }
    }
    return false;
}

function unLogin($cookiePre='isux'){
    $sessionKey = $cookiePre . '_user';
    global $logined, $user;
    unset($_SESSION[$sessionKey]);
    $logined = false;
    $user = NULL;
}

function updateUser(array $user, $cookiePre='isux') {
    $sessionKey = $cookiePre . '_user';
    $_SESSION[$sessionKey] = $user;
}